﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using ComicIsland.Common;
using ComicIsland.Common.Entities.ComicDatabase;
using ComicIsland.Common.StorageHelper;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace ComicIsland.App.Views.ReadComic
{
    public partial class ComicReaderPage : PhoneApplicationPage
    {
        private int comicId = 0, comicPartId = 0;
        private string comicTitle = string.Empty, comicPartTitle = string.Empty;
        //
        ObservableCollection<DbImage> dbImages = new ObservableCollection<DbImage>();
        DbImage currentDbImageItem = null;
        private int currentDbImageIndex = 0;

        public ComicReaderPage()
        {
            InitializeComponent();
            //            
            this.ManipulationDelta += ComicReaderPage_ManipulationDelta;
            this.ManipulationStarted += ComicReaderPage_ManipulationStarted;
            this.ManipulationCompleted += ComicReaderPage_ManipulationCompleted;
        }


        void ComicReaderPage_ManipulationCompleted(object sender, System.Windows.Input.ManipulationCompletedEventArgs e)
        {
            e.Handled = true;
            FrameworkElement originalSource = e.OriginalSource as FrameworkElement;
            Point point = e.ManipulationContainer.TransformToVisual(this).Transform(e.ManipulationOrigin);
            if (this.currentDbImageIndex <= 0 && (e.TotalManipulation.Translation.X > 0 || e.TotalManipulation.Translation.X == 0 && point.X < 160 || point.Y < 160 && point.X < 320))
            {
                MessageToastManager.Show("已经是本章节的首页了！");
                return;
            }
            if (this.currentDbImageIndex >= this.dbImages.Count - 1 && (e.TotalManipulation.Translation.X < 0 || e.TotalManipulation.Translation.X == 0 && point.X >= 320 || point.Y > 640 && point.X > 160))
            {
                MessageToastManager.Show("已经是本章节的最后一页了！");
                return;
            }
            this.OnTouchFlick(originalSource, point, e.TotalManipulation.Translation.X);
        }

        void ComicReaderPage_ManipulationStarted(object sender, System.Windows.Input.ManipulationStartedEventArgs e)
        {
            e.Handled = true;
            object originalSource = e.OriginalSource;
            e.ManipulationContainer.TransformToVisual(this).Transform(e.ManipulationOrigin);
        }

        private void ComicReaderPage_ManipulationDelta(object sender, System.Windows.Input.ManipulationDeltaEventArgs e)
        {
            e.Handled = true;
            object originalSource = e.OriginalSource;
            e.ManipulationContainer.TransformToVisual(this).Transform(e.ManipulationOrigin);

            this.OnTouchDrag(e.DeltaManipulation.Translation.X);
        }

        private void OnTouchFlick(FrameworkElement touchTarget, Point position, double xTotal)
        {
            double num = xTotal;
            if (num < 0)
            {
                LogHelper.LogInfo("Next");
                SetImageNextOrPrevious(NextOrPrevious.Next);
                return;
            }
            if (num > 0)
            {
                LogHelper.LogInfo("Previous");
                SetImageNextOrPrevious(NextOrPrevious.Previous);
                return;
            }
            if (position.X < 160 || position.Y < 160 && position.X < 320)
            {
                LogHelper.LogInfo("Previous");
                SetImageNextOrPrevious(NextOrPrevious.Previous);
                return;
            }
            if (position.X > 320 || position.Y > 640 && position.X > 160)
            {
                LogHelper.LogInfo("Next");
                SetImageNextOrPrevious(NextOrPrevious.Next);
                return;
            }
        }

        public enum NextOrPrevious
        {
            None,
            Next,
            Previous
        }

        private void SetImageNextOrPrevious(NextOrPrevious nop)
        {
            if (!(this.dbImages != null && this.dbImages.Count > 0))
            {
                return;
            }
            //            
            switch (nop)
            {
                case NextOrPrevious.None:
                    break;
                case NextOrPrevious.Next:
                    this.currentDbImageIndex++;
                    break;
                case NextOrPrevious.Previous:
                    this.currentDbImageIndex--;
                    break;
            }
            if (this.currentDbImageIndex <= 0)
            {
                MessageToastManager.Show("已经是本章节的首页了！");
                return;
            }
            if (this.currentDbImageIndex >= this.dbImages.Count - 1)
            {
                MessageToastManager.Show("已经是本章节的最后一页了！");
                return;
            }
            this.currentDbImageItem = this.dbImages[this.currentDbImageIndex];
            string filePath = string.Concat(KEYS.ComicIslandCacheDirectory, "/", KEYS.CacheImagePrefix, this.currentDbImageItem.ComicId, "_",
                this.currentDbImageItem.PartId, "_", MD5.GetMd5String(this.currentDbImageItem.ImageUrl));
            this.BindImage(filePath,this.currentDbImageItem);
            //
            this.sliderProgress.Value = this.currentDbImageIndex;
        }



        private void OnTouchDrag(double xDelta)
        {

        }

        private void image_Hold(object sender, System.Windows.Input.GestureEventArgs e)
        {
            LogHelper.LogInfo("image_Hold");
            this.popupBottom.Width = Application.Current.Host.Content.ActualWidth;
            this.popupBottom.IsOpen = true;
        }

        private void sliderProgress_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            int currentValue = (int)this.sliderProgress.Value;
            NextOrPrevious currentNop = NextOrPrevious.None;
            if (currentValue > this.currentDbImageIndex)
                currentNop = NextOrPrevious.Next;
            else if (currentValue < this.currentDbImageIndex)
                currentNop = NextOrPrevious.Previous;
            this.txtProgress.Text = string.Concat(this.currentDbImageIndex, "/", this.dbImages.Count.ToString());
            //SetImageNextOrPrevious(currentNop);

        }












        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            string tmpComicId, tmpComicPartId;
            base.NavigationContext.QueryString.TryGetValue("comicId", out tmpComicId);
            int.TryParse(tmpComicId, out comicId);
            if (comicId <= 0)
            {
                base.NavigationService.GoBack();
                return;
            }
            base.NavigationContext.QueryString.TryGetValue("comicPartId", out tmpComicPartId);
            int.TryParse(tmpComicPartId, out comicPartId);
            if (comicPartId <= 0)
            {
                base.NavigationService.GoBack();
                return;
            }
            //
            LoadComicChapterImage();

        }



        void LoadComicChapterImage()
        {
            //加载缓存中的图片
            this.LoadCacheImage();
            //获取网络图片
        }

        /// <summary>
        /// 加载缓存中的图片
        /// </summary>
        void LoadCacheImage()
        {
            this.dbImages = App.comicDbHelper.ImageGetByComicIdAndChapterId(this.comicId, this.comicPartId);
            if (!(this.dbImages != null && this.dbImages.Count > 0))
            {
                return;
            }
            //
            //imageDown.Source = new BitmapImage(new Uri("http://cartoon.jide123.cc/manhuatuku/3670/201491018226249.jpg", UriKind.Absolute));
            this.currentDbImageIndex = 0;
            this.currentDbImageItem = this.dbImages[this.currentDbImageIndex];
            string filePath = string.Concat(KEYS.ComicIslandCacheDirectory, "/", KEYS.CacheImagePrefix, this.currentDbImageItem.ComicId, "_",
                this.currentDbImageItem.PartId, "_", MD5.GetMd5String(this.currentDbImageItem.ImageUrl));
            this.BindImage(filePath,this.currentDbImageItem);
            this.sliderProgress.Maximum = this.dbImages.Count;
            this.sliderProgress.Minimum = 0;
            this.sliderProgress.Value = 0;
            this.txtProgress.Text = string.Concat("0/", this.dbImages.Count);

        }

        /// <summary>
        /// 绑定图片
        /// </summary>
        void BindImage(string filePath,DbImage dbImage)
        {
            try
            {
                using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (!IsolatedStorageHelper.Instance.FileExists(filePath))
                    {
                        BitmapImage image = new BitmapImage();
                        image.UriSource = new Uri(dbImage.ImageUrl, UriKind.Absolute);
                    }
                    else
                    {
                        using (IsolatedStorageFileStream isoStream = store.OpenFile(filePath, FileMode.Open))
                        {
                            Stream fileStream = new MemoryStream();
                            isoStream.CopyTo(fileStream);

                            isoStream.Close();
                            isoStream.Dispose();
                            store.Dispose();

                            BitmapImage image = new BitmapImage();
                            Stream source = fileStream;
                            image.SetSource(source);

                            this.image.Source = image;
                            ImageHeightWidthByOrientationChanged();
                        }
                    }
                }
            }
            catch (Exception err)
            {
                LogHelper.LogError(err.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            }
        }

        void ImageHeightWidthByOrientationChanged()
        {
            if (PageOrientation.LandscapeLeft == this.Orientation || PageOrientation.LandscapeRight == this.Orientation)
            {
                this.image.Width = Application.Current.Host.Content.ActualHeight;
            }
            if (PageOrientation.PortraitUp == this.Orientation)
            {
                this.image.Width = Application.Current.Host.Content.ActualWidth;
                this.image.Height = Application.Current.Host.Content.ActualHeight;
            }
        }


        private void PhoneApplicationPage_OrientationChanged(object sender, OrientationChangedEventArgs e)
        {
            ImageHeightWidthByOrientationChanged();
        }

        private void imageDown_ImageOpened(object sender, RoutedEventArgs e)
        {
            //加载状态
        }

        private void GestureListener_DoubleTap(object sender, GestureEventArgs e)
        {
            LogHelper.LogInfo("GestureListener_DoubleTap");
        }

        private void GestureListener_DragCompleted(object sender, DragCompletedGestureEventArgs e)
        {

        }

        private void GestureListener_PinchStarted(object sender, PinchStartedGestureEventArgs e)
        {

        }

        private void GestureListener_PinchDelta(object sender, PinchGestureEventArgs e)
        {

        }

        private void GestureListener_PinchCompleted(object sender, PinchGestureEventArgs e)
        {

        }

        private void GestureListener_DragStarted(object sender, DragStartedGestureEventArgs e)
        {

        }

        private void GestureListener_DragDelta(object sender, DragDeltaGestureEventArgs e)
        {

        }








    }
}